package com.example.nutritionmate.service;

import com.example.nutritionmate.dto.UpdateUserDTO;
import com.example.nutritionmate.dto.UserDTO;
import com.example.nutritionmate.entity.User;
import com.example.nutritionmate.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 根据用户名查找用户
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    // 创建新用户并编码密码
    public User createUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRegister_date(LocalDate.now());
        return userRepository.save(user);
    }

    // 将 User 实体转换为 UserDTO
    public UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setUserId(user.getUserId());
        dto.setUsername(user.getUsername());
        dto.setGender(user.getGender());
        dto.setAge(user.getAge());
        dto.setWeight(user.getWeight());
        dto.setHeight(user.getHeight());
        dto.setPeriod(user.getPeriod());
        dto.setTargetCalories(user.getTarget_calories());
        dto.setRegisterDate(user.getRegister_date());
        return dto;
    }

    // 更新用户信息（不编码密码）
    public User updateUser(String username, UpdateUserDTO updateUserDTO) {
        Optional<User> optionalUser = userRepository.findByUsername(username);
        if (optionalUser.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        User user = optionalUser.get();

        // 更新字段，如果DTO中的字段不为null，则进行更新
        if (updateUserDTO.getGender() != null) {
            user.setGender(updateUserDTO.getGender());
        }
        if (updateUserDTO.getAge() != null) {
            user.setAge(updateUserDTO.getAge());
        }
        if (updateUserDTO.getWeight() != null) {
            user.setWeight(updateUserDTO.getWeight());
        }
        if (updateUserDTO.getHeight() != null) {
            user.setHeight(updateUserDTO.getHeight());
        }
        if (updateUserDTO.getPeriod() != null) {
            user.setPeriod(updateUserDTO.getPeriod());
        }
        user.setTarget_calories(calculateCalorie(user));

        // 只保存不编码密码
        return userRepository.save(user);
    }


    private int calculateCalorie(User user) {
        // 计算基础代谢率 (BMR)
        double bmr;
        if (user.getGender() != null && user.getGender().equals(1)) {
            bmr = 88.362 + (13.397 * user.getWeight()) + (4.799 * user.getHeight()) - (5.677 * user.getAge());
        } else {
            bmr = 447.593 + (9.247 * user.getWeight()) + (3.098 * user.getHeight()) - (4.330 * user.getAge());
        }

        // 计算每日总能量消耗 (TDEE)
//        double activityFactor = getActivityFactor(user.getActivityLevel()); // 假设用户有活动水平字段
        double tdee = bmr * 1.2;

        // 根据目标状态调整卡路里
        Integer period = user.getPeriod();
        switch (period) {
            case 1:
                tdee -= 500; // 减脂期每日减少500卡路里
                break;
            case 2:
                tdee += 500; // 增肌期每日增加500卡路里
                break;
            // 保持期不需要调整
        }

        return (int) Math.round(tdee); // 四舍五入为整数
    }

    // 获取活动系数
    private double getActivityFactor(String activityLevel) {
        switch (activityLevel.toLowerCase()) {
            case "久坐":
                return 1.2;
            case "轻度活动":
                return 1.375;
            case "中度活动":
                return 1.55;
            case "高度活动":
                return 1.725;
            case "极高活动":
                return 1.9;
            default:
                return 1.2; // 默认值
        }
    }
}
